package com.avic.modules.storage.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ResponseUtils {
    public static ResponseEntity<byte[]> getResponseEntity(String fileName, String fileAbsPath, boolean deleteOnExit) throws IOException {
        if (Files.exists(Paths.get(fileAbsPath))) {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentDispositionFormData("attachment", fileName);
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            File file = new File(fileAbsPath);
            InputStream fileStream = new FileInputStream(file);
            byte[] bytes;
            bytes = readInputStream(fileStream);
            fileStream.close();
            if(deleteOnExit){
                file.deleteOnExit();
            }
            return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        inputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    private ResponseUtils() {
    }

    //内存中的文件字节数组发送到客户端
    public static void sendFileByteArray(HttpServletResponse response, byte[] byteArray, String fileName,
                                         String responseContentType,String responseContentDisposition) throws Exception {
        // response.setCharacterEncoding("utf-8");
        // "application/vnd.ms-excel;charset=utf-8"
        // "application/octet-stream;charset=UTF-8"
        if(responseContentType!=null) {
            response.setContentType(responseContentType);
        }else {
            response.setContentType("application/octet-stream;charset=UTF-8");
        }
        if(responseContentDisposition!=null) {
            response.addHeader("Content-Disposition", responseContentDisposition);
        }else {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }
        response.addHeader("Content-Length", "" + byteArray.length);
        response.addHeader("pargam", "no-cache");
        response.getOutputStream().write(byteArray);
        response.getOutputStream().flush();
    }

}
